import { SetupContext, computed, provide, ref, toRefs, watch } from 'vue'
import { CheckboxGroupEmit, CheckboxGroupProps, checkboxGroupInjectionKey } from '../checkbox-group-types'

export default function (props: CheckboxGroupProps, ctx: SetupContext<CheckboxGroupEmit>) {
  const { disabled, isTitle, direction } = toRefs(props)
  const changeHandle = (cs: Array<string | number>) => {
    checks.value = cs
    ctx.emit('change', cs)
  }
  const checks = computed({
    get() {
      return props.modelValue
    },
    set(val) {
      ctx.emit('update:modelValue', val)
    }
  })
  watch(
    () => checks.value,
    (val) => {
      ctx.emit('change', val)
    },
    { deep: true }
  )
  provide(checkboxGroupInjectionKey, {
    disabled,
    checks,
    isTitle,
    direction,
    changeHandle
  })
  return {
    disabled,
    checks,
    isTitle,
    direction,
    changeHandle
  }
}
